#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render, HttpResponse, redirect
import random
from utils.tencent.sms import send_sms_single
from web import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.conf import settings
import random
from django_redis import get_redis_connection
# Create your views here.


class RegisiterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3-9])\d{9}$', '手机号格式错误')])
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(),
        max_length=20,
        min_length=8,
        error_messages={
            'min_length': '密码长度不能小于8个字符',
            'max_length': '密码长度不能大于20个字符',
        }
    )
    confirm_password = forms.CharField(
        label='重复密码',
        widget=forms.PasswordInput(attrs={'placeholder': '请重复输入密码'}),
        max_length=20,
        min_length=8,
        error_messages={
            'min_length': '重复密码长度不能小于8个字符',
            'max_length': '重复密码长度不能大于20个字符',
        }
    )
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'placeholder': '请输入验证码'}))

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control %s'%(field.label,)
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)
    def clean_username(self):
        '''
        判断用户名是否重复
        :return:
        '''
        username = self.cleaned_data['username']
        exists = models.UserInfo.objects.filter(username=user).exists()
        if exists:
            raise ValidationError('用户名已存在')
        return username

    def clean_email(self):
        '''
        判断邮箱是否存在
        :return:
        '''
        emile = self.cleaned_data['email']
        exists = models.UserInfo.objects.filter(email=emile).exists()
        if exists:
            raise ValidationError('邮箱已存在')
        return emile

    def clean_confirm_password(self):
        '''
        验证两次密码是否一致
        :return:
        '''
        comfirm_password = self.cleaned_data['confirm_password']
        password = self.cleaned_data['password']
        if password != comfirm_password:
            raise ValidationError('两次密码不一致')
        return comfirm_password

    def clean_mobile_phone(self):
        '''
        手机号校验
        :return:
        '''
        mobile_phone = self.cleaned_data['mobile_phone']
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if exists:
            raise ValidationError('手机号已注册')
        return mobile_phone

    def clean_code(self):
        '''
        验证码校验
        :return:
        '''
        code = self.cleaned_data['code']
        mobile_phone = self.cleaned_data['mobile_phone']
        if len(code) != 6:
            raise ValidationError('验证码长度错误')
        conn = get_redis_connection()
        redis_code = conn.get(mobile_phone)
        if not redis_code:
            raise ValidationError('验证码失效或未发送，请重新发送')
        redis_str_code = redis_code.decode('utf8')
        if code.strip() != redis_str_code:
            raise ValidationError('验证码错误，请重新输入')
        return code

class SendSmsForm(forms.Form):

    mobile_phone = forms.CharField(label='手机号',validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误')])

    def __init__(self,request,*args,**kwargs):
        '''
        把request传入钩子函数中
        '''
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_mobile_phone(self):
        '''手机号校验钩子'''
        mobile_phone = self.cleaned_data['mobile_phone']
        # 判断短信模板是否有问题
        tpl = self.request.GET.get('tpl')
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
        if not template_id:
            raise ValidationError('短信模板错误')

        # 校验数据库中是否已经有此手机号
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if exists:
            raise ValidationError('手机号已存在')
        code = random.randrange(100000,999999)

        # 发送短信
        sms = send_sms_single(mobile_phone,template_id,[code,])
        if sms['result'] != 0:
            raise  ValidationError('短信发送失败,{}'.format(sms['errmsg']))

        # 验证码写入redis
        conn = get_redis_connection()
        conn.set(mobile_phone,code,ex=300)
        return mobile_phone


